package com.wuliupai.delivery.wuliupaidelivery.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.wuliupai.delivery.wuliupaidelivery.bean.LocationBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.CommConstants;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;

public class LocationService extends Service {


    private LocationClient mLocationClient;
    private MyLocationListener mMyLocationListener;

    private final String CommitLocationURL = Value.PATH_SERVER + InterfaceNet.Net_CommitLocation;
    private OkHttpClient.Builder clientBuilder;

    private LocationBean locationBean;

    private boolean canUpload = true;//是否可以上传

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        locationBean = new LocationBean();

        clientBuilder = new OkHttpClient.Builder();
        clientBuilder.readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(100, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(80, TimeUnit.SECONDS);//设置连接超时时间

        mLocationClient = new LocationClient(getApplicationContext());
        mMyLocationListener = new MyLocationListener();

        mLocationClient.registerLocationListener(mMyLocationListener);
        initLocation();
        mLocationClient.requestLocation();

        Observable.interval(0, 1, TimeUnit.MINUTES)
                .subscribe(aLong -> {
                    //需要执行的内容
                    canUpload = true;
                    mLocationClient.start();
                });
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度，默认值
//        option.setScanSpan(ScanSpanMin * 60 * 1000);// 设置发起定位请求的间隔时间
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    /**
     * 实现定位回调监听
     */
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (canUpload) {
                uploadLocation(location.getLongitude(), location.getLatitude());

            }
        }
    }

    /**
     * 上传当前位置
     *
     * @param lat
     * @param lot
     */
    private void uploadLocation(double lat, double lot) {

        canUpload = false;
        mLocationClient.stop();

        try {
            locationBean.setGps_x(lat + "");
            locationBean.setGps_y(lot + "");

            FormBody.Builder builder = new FormBody.Builder();
            String requestJson = JsonUtils.createJsonString(locationBean);
            builder.add("info", JsonUtils.aes(requestJson));
            RequestBody requestBody = builder.build();

            //构建post请求
            Request request = new Request.Builder().url(CommitLocationURL).post(requestBody).build();
            clientBuilder.build().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtils.log("上传地址发生异常——\t" + e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        LogUtils.log("上传地址发生成功——\t");
                    } else {
                        LogUtils.log("上传地址发生异常——\terrCode：" + response.code() + "\terrMsg：" + response.message());
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}